package pers.qianyu.month_202012.date_20201215;

import org.junit.*;

/**
 * 494. 目标和
 * https://leetcode-cn.com/problems/target-sum/
 *
 * @author mizzle rain
 * @date 2020-12-15 10:44
 */
public class FindTargetSumWays {
    /**
     * 动态规划解法
     */
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum < S || ((sum + S) & 1) == 1) {
            return 0;
        }
        sum = (sum + S) >> 1;
        int[] dp = new int[sum + 1];
        dp[0] = 1;
        for (int num : nums) {
            for (int j = sum; j >= num; j--) {
                dp[j] += dp[j - num];
            }
        }
        return dp[sum];
    }

    @Test
    public void test1() {
        int result = new FindTargetSumWays()
                .findTargetSumWays(new int[]{1, 1, 1, 1, 1}, 3);
        System.out.println("result = " + result);
    }
}
